import pygame
from math import *
from pygame.locals import *

pygame.init()

# "settings" so to speak
WIDTH = 640
HEIGHT = 480

SCALEWIDTH = 4.0 # length of the x-axis over the width of the screen
SCALEHEIGHT = 3.0 # height of the y-axis over the height of the screen
# end settings

# User defined data
A = (1.0, 0.0)
B = (0.5, 0.87)
C = (-0.5, 0.87)
D = (-1.0, 0.0)
E = (-0.5, -0.87)
F = (0.5, -0.87)

# the functions to determine the colors, modify the functions only
funcs = { "r": lambda x, y: distance((x, y), A)-distance((x, y), D), \
    "g": lambda x, y: distance((x, y), B)-distance((x, y), E), \
    "b": lambda x, y: distance((x, y), C)-distance((x, y), F)}
    # the functions that make the pattern
    
def distance(a, b): 
    """helper method, for ease of use, slow though, be careful"""
    return sqrt((a[0]+b[0])**2+(a[1]+b[1])**2)

def render_pattern(pattern, surf):
    """Render the pattern on a surf using the given pattern"""
    pixels = pygame.PixelArray(surf)
    for row in range(len(pixels)):
        for col in range(len(pixels[row])):
            x, y = convert_coords(col, row)
            pixels[row][col] = (convert_colors(pattern["r"](x, y)), \
            convert_colors(pattern["g"](x, y)), \
            convert_colors(pattern["b"](x, y)))
    return 

def convert_coords(row, col):
    """Convert screen coordinates to the coordinates that the functions use"""
    return ((col-(WIDTH/2))/(WIDTH/SCALEWIDTH), -(row-(HEIGHT/2))/(HEIGHT/SCALEHEIGHT))
    
def convert_colors(val):
    """Convert the value from 0.0 to 2.0 to a number from 0 to 255"""
    return -((val%2)*((val%2)-2))*255

def main():
    clock = pygame.time.Clock()
    screen = pygame.display.set_mode((WIDTH, HEIGHT), 32)
    render_pattern(funcs, screen)
    while 1:
        clock.tick(1) # don't waste cpu, displaying a static image!
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == QUIT:
                raise SystemExit("Closed by user.")
            if event.type == KEYDOWN and event.key == K_ESCAPE:
                raise SystemExit("Closed by user.")
        
if __name__ == "__main__":
    main()